package v2;

import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;

import javax.swing.JFrame;
import javax.swing.Timer;

public class ParticleViewer extends JFrame {

	private static final long serialVersionUID = 1261731945730393666L;
	private ParticleManager manager;
	private Timer timer;

	public ParticleViewer(Dimension d) {
		setPreferredSize(d);
		setSize(d);

		this.addMouseListener(new ClickAdder());

		manager = new ParticleManager(d);

		Stepper s = new Stepper();
		final int DELAY = 1;
		timer = new Timer(DELAY, s);
	}

	public void start() {
		timer.start();
	}

	public void add(ParticleShape p) {
		manager.add(p.getCollection());

		Graphics2D g = (Graphics2D) this.getGraphics();
		for (Particle part : p.getCollection()) {
			drawParticle(part, g);
		}
	}
	public void add(Particle p){
		manager.add(p);
		Graphics2D g = (Graphics2D) this.getGraphics();
		drawParticle(p, g);
	}

	private void drawAllParticles() {
		Graphics2D g = (Graphics2D) this.getGraphics();
		// g.clearRect(0, 0, getWidth(), getHeight());
		for (Particle p : manager.getParticles()) {
			int prevX = (int) (p.getState().getPX() - p.getState().getVX());
			int prevY = (int) (p.getState().getPY() - p.getState().getVY());

			g.clearRect(prevX - 1, prevY - 1, 5, 5);
			drawParticle(p, g);
		}
	}

	private void drawParticle(Particle p, Graphics2D g) {
		int x = (int) p.getState().getPX();
		int y = (int) p.getState().getPY();
		p.createDrawing(g, x, y);
	}

	private class ClickAdder implements MouseListener {
		@Override
		public void mouseClicked(MouseEvent arg0) {
			Particle p = new Particle(arg0.getX(), arg0.getY());
			manager.add(p);

			Graphics2D g = (Graphics2D) getGraphics();
			drawParticle(p, g);
		}

		@Override
		public void mouseEntered(MouseEvent arg0) {
		}

		@Override
		public void mouseExited(MouseEvent arg0) {
		}

		@Override
		public void mousePressed(MouseEvent arg0) {
		}

		@Override
		public void mouseReleased(MouseEvent arg0) {
		}
	}

	private class Stepper implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent arg0) {
			clearEdges(manager.step());
			drawAllParticles();
		}
	}

	private void clearEdges(ArrayList<Particle> artifacts) {
		if (artifacts.size() >= 0) {
			Graphics2D g = (Graphics2D) this.getGraphics();
			for (Particle p : artifacts) {
				int prevX = (int) (p.getPoint().getX() - p.getState()
						.getVX());
				int prevY = (int) (p.getPoint().getY() - p.getState()
						.getVY());

				g.clearRect(prevX - 1, prevY - 1, 5, 5);
			}
		}
	}
}
